/** ResultsPanel */
package client.ui.panel;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.logging.Logger;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;

import org.json.JSONObject;

import client.ClientManager;
import client.EventBus;
import client.events.PatientEdit;
import client.io.ClientIO;
import domain.action.Action;
import domain.patient.Patient;
import domain.session.Request;
import domain.session.Response;
import domain.user.SystemUser;
import domain.user.User;

/**
 * @author jessienewman
 * @version $Revision: 1.0 $
 */
public class ResultsPanel extends DefaultPanel {


	/**
	 * Field LOGGER.
	 */
	private static final Logger LOGGER = Logger.getLogger(ClientManager.class.getName());

	/**
	 * Field results.
	 */
	private JPanel results;

	/**
	 * Field c.
	 */
	private GridBagConstraints c;

	/**
	 * Constructor for ResultsPanel.
	 */
	public ResultsPanel() {
		//Results
		results = new JPanel();
		results.setBackground(Color.WHITE);
		results.setLayout(new GridBagLayout());
		c = new GridBagConstraints();
		this.add(results, BorderLayout.CENTER);
		LOGGER.info("Results Panel created");
	}

	/**
	 * Method addResults.
	 * @param resultsList List<User>
	 */
	public void addResults(List<User> resultsList) {
		results.removeAll();
		if (resultsList.size() == 0) {
			return;
		}

		//this.patientList = patientList;
		c.gridx = 0;
		c.gridy = 0;
		for (final User u : resultsList) {
			JButton button = new JButton("<html><u>" + 
					((SystemUser) u).getFullName() + "</u></html>");
			button.setBorder(BorderFactory.createEmptyBorder());
			button.setForeground(Color.BLUE);
			results.add(button, c);
			button.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent event) {
					JSONObject patientJson = new JSONObject();
					patientJson.put("patientId", u.getUserId());
					ClientIO.sendRequest(new Request(Action.GET_PATIENT, patientJson));
					Response response = ClientIO.getResponse();
					if (response.isSuccessful()) {
						JSONObject responseJson = response.getJSON();
						Patient filledPatient = new Patient(responseJson);
						EventBus.BUS.fireEvent(new PatientEdit(filledPatient));
					}
					EventBus.BUS.fireEvent(new PatientEdit((SystemUser) u));
				}
			});
			c.gridy++;
		}
		//results.repaint();
	}
}
